/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import relationalStore from "@ohos.data.relationalStore"
import { GPData,TIndexInfo,TGeneralInfo,TPowerSensorInfo,TPowerAppInfo,SceneInfo, PerformInfo, FrameRateInfo,GPUCounterInfo } from '../entity/DatabaseEntity';
import {UserInfo, UserType} from "../entity/UserEntity";
import { dbVersion, dbName, sql_t_index_info, task_powerSensor_info, task_powerApp_info, task_powerThread_info, sql_t_user_info_delete, sql_t_perform_info ,sql_t_gpu_counter_info,sql_t_used_res_info} from "../constant/ConstantSQL"
import SPLogger from '../utils/SPLogger'
import { DaoConfig } from "../db/DaoConfig"
import { DbUtils } from "../utils/DbUtils"
import { DbCallBackImp } from "../db/QueryCallBackImp"
import fs from '@ohos.file.fs';
import { updateUploadStatus } from './LocalRepository';

const TAG = "DatabaseUtils"

export default {

    //创建表(T_INDEX_INFO T_GENERAL_INFO)
    async createTable(pathSuffix: number): Promise<void> {
        const myMap = new Map()
        myMap.set('t_index_info', sql_t_index_info);
        myMap.set('task_powersensor_info', task_powerSensor_info);
        myMap.set('task_powerapp_info', task_powerApp_info);
        myMap.set('task_powerthread_info', task_powerThread_info);
        myMap.set("t_gpu_counter_info", sql_t_gpu_counter_info)
        myMap.set("t_used_res_info", sql_t_used_res_info)

        let config = new DaoConfig()
        config.setDbName(pathSuffix + ".db")
        let db = new DbUtils(config)
        db.setCallback(new DbCallBackImp())
        db.execCreate(myMap)
    },

    //插入表( T_GENERAL_INFO)
    insertGeneraData(tableName: string, tGeneralInfo: TGeneralInfo) {
        let config = new DaoConfig()
        config.setDbName(dbName)
        config.setTableName(tableName)
        let db = new DbUtils(config)
        var strMap = new Map;
        for (let k of Object.keys(tGeneralInfo)) {
            strMap.set(k, tGeneralInfo[k])
        }
        const valueInsert = Object.fromEntries(strMap)
        db.save(valueInsert)
    },

    // 插入表 ( T_PERFORM_INFO)
    insertPerformData(tableName:string, performInfo: PerformInfo) {
        let config = new DaoConfig()
        config.setDbName(dbName)
        config.setTableName(tableName)
        let db = new DbUtils(config)
        var strMap = new Map;
        for (let k of Object.keys(performInfo)){
            strMap.set(k, performInfo[k])
        }
        const valueInsert = Object.fromEntries(strMap)
        db.save(valueInsert)
    },

    // 插入表 (T_FRAMERATE_INFO)帧率测试信息
    insertFrameRateData(tableName:string, frameRateInfo: FrameRateInfo) {
        let config = new DaoConfig()
        config.setDbName(dbName)
        config.setTableName(tableName)
        let db = new DbUtils(config)
        var strMap = new Map;
        for (let k of Object.keys(frameRateInfo)){
            strMap.set(k, frameRateInfo[k])
        }
        const valueInsert = Object.fromEntries(strMap)
        db.save(valueInsert)
    },


    //插入表(T_INDEX_INFO)
    insertData(tableName: string, pathSuffix: number, tIndexInfo: TIndexInfo) {
        let config = new DaoConfig()
        config.setDbName(pathSuffix + '.db')
        config.setTableName(tableName)
        let db = new DbUtils(config)
        var strMap = new Map;
        for (let k of Object.keys(tIndexInfo)) {
            strMap.set(k, tIndexInfo[k]);

        }
        const valueInsert = Object.fromEntries(strMap)
        db.save(valueInsert)
    },

    // 修改上传状态
    async changeUploadStatus(sessionId: String) {
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: dbName,
                securityLevel: relationalStore.SecurityLevel.S1
            };
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG).then(async (rdbStore) => {
                let strSQL: string = "UPDATE t_general_info SET upStatus = '1' WHERE sessionId LIKE ?"
                return rdbStore.executeSql(strSQL, [sessionId+''])
            })
        }catch(err) {
            SPLogger.ERROR(TAG, "resultSet changeUploadStatus err:" + err)
        }
    },
    async updateSyncStatus(sessionIds?:string[]){
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: dbName,
                securityLevel: relationalStore.SecurityLevel.S1
            };
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG).then(async (rdbStore) => {
                if (sessionIds && sessionIds.length>0) {
                    sessionIds=sessionIds.map(item=>{return `'${item}'`})
                    let ids=sessionIds.join(',')
                    let strSQL: string = `UPDATE t_general_info SET syncStatus = '1' WHERE sessionId IN (${ids})`
                    return rdbStore.executeSql(strSQL)
                }else{
                    let strSQL: string = "UPDATE t_general_info SET syncStatus = '1'"
                    return rdbStore.executeSql(strSQL)
                }

            })
        }catch(err) {
            SPLogger.ERROR(TAG, "resultSet changeUploadStatus err:" + err)
        }
    },
    async queryGeneralBySessionId(sessionId:string): Promise<TGeneralInfo>{
        let generalInfo:TGeneralInfo
        const STORE_CONFIG: relationalStore.StoreConfig = {
            name: dbName,
            securityLevel: relationalStore.SecurityLevel.S1
        };
        return await relationalStore.getRdbStore(globalThis.abilityContext,STORE_CONFIG).then(rdbStore=>{
            return rdbStore.query(new relationalStore.RdbPredicates('t_general_info').equalTo('sessionId',sessionId))
        }).then(resultSet=>{
            while (resultSet.goToNextRow()) {
                let sessionId = resultSet.getString(resultSet.getColumnIndex("sessionId"))
                let taskId = resultSet.getString(resultSet.getColumnIndex("taskId"))
                let appName = resultSet.getString(resultSet.getColumnIndex("appName"))
                let appVersion = resultSet.getString(resultSet.getColumnIndex("appVersion"))
                let packageName = resultSet.getString(resultSet.getColumnIndex("packageName"))
                let startTime = resultSet.getString(resultSet.getColumnIndex("startTime"))
                let endTime = resultSet.getString(resultSet.getColumnIndex("endTime"))
                let testDuration = resultSet.getLong(resultSet.getColumnIndex("testDuration"))
                let taskName = resultSet.getString(resultSet.getColumnIndex("taskName"))
                let board = resultSet.getString(resultSet.getColumnIndex("board"))
                let deviceTypeName = resultSet.getString(resultSet.getColumnIndex("deviceTypeName"))
                let brand = resultSet.getString(resultSet.getColumnIndex("brand"))
                let version = resultSet.getString(resultSet.getColumnIndex("version"))
                let sn = resultSet.getString(resultSet.getColumnIndex("sn"))
                let upStatus = resultSet.getString(resultSet.getColumnIndex("upStatus"))
                let projectId = resultSet.getString(resultSet.getColumnIndex("projectId"))
                let deviceName = resultSet.getString(resultSet.getColumnIndex("deviceName"))
                let cpuCluster = resultSet.getString(resultSet.getColumnIndex("cpuCluster"))
                let uploadTaskId = resultSet.getString(resultSet.getColumnIndex("uploadTaskId"))
                let syncStatusStr=resultSet.getColumnIndex("syncStatus")
                let syncStatus = syncStatusStr ? resultSet.getString(syncStatusStr) : '0'
                let tGeneralInfo = new TGeneralInfo(
                    sessionId, taskId, appName, appVersion, packageName, Number(startTime).valueOf(), Number(endTime).valueOf(), testDuration, taskName,
                    upStatus, deviceName, cpuCluster, uploadTaskId
                )
                tGeneralInfo.board = board
                tGeneralInfo.deviceTypeName = deviceTypeName
                tGeneralInfo.brand = brand
                tGeneralInfo.version = version
                tGeneralInfo.sn = sn
                tGeneralInfo.upStatus = upStatus
                tGeneralInfo.projectId = projectId
                tGeneralInfo.syncStatus = syncStatus
                generalInfo=tGeneralInfo
            }
            return generalInfo
        })
    },
    //查询表( T_GENERAL_INFO)
    async queryGeneralData(): Promise<Array<TGeneralInfo>> {
        const queryColumns = ["sessionId",
            "startTime", "taskId", "appName", "appVersion", "packageName", "endTime", "testDuration", "taskName", "board",
            "deviceTypeName", "brand", "version", "sn", "upStatus", "projectId", "deviceName", "cpuCluster", "uploadTaskId"
        ]
        let results = Array<TGeneralInfo>()
        const STORE_CONFIG: relationalStore.StoreConfig = {
            name: dbName,
            securityLevel: relationalStore.SecurityLevel.S1
        };
        await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
            .then(rdbStore => {
                return rdbStore.query(new relationalStore.RdbPredicates('t_general_info').orderByDesc('startTime'))
                }).then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let sessionId = resultSet.getString(resultSet.getColumnIndex("sessionId"))
                        let taskId = resultSet.getString(resultSet.getColumnIndex("taskId"))
                        let appName = resultSet.getString(resultSet.getColumnIndex("appName"))
                        let appVersion = resultSet.getString(resultSet.getColumnIndex("appVersion"))
                        let packageName = resultSet.getString(resultSet.getColumnIndex("packageName"))
                        let startTime = resultSet.getString(resultSet.getColumnIndex("startTime"))
                        let endTime = resultSet.getString(resultSet.getColumnIndex("endTime"))
                        let testDuration = resultSet.getLong(resultSet.getColumnIndex("testDuration"))
                        let taskName = resultSet.getString(resultSet.getColumnIndex("taskName"))
                        let board = resultSet.getString(resultSet.getColumnIndex("board"))
                        let deviceTypeName = resultSet.getString(resultSet.getColumnIndex("deviceTypeName"))
                        let brand = resultSet.getString(resultSet.getColumnIndex("brand"))
                        let version = resultSet.getString(resultSet.getColumnIndex("version"))
                        let sn = resultSet.getString(resultSet.getColumnIndex("sn"))
                        let upStatus = resultSet.getString(resultSet.getColumnIndex("upStatus"))
                        let projectId = resultSet.getString(resultSet.getColumnIndex("projectId"))
                        let deviceName = resultSet.getString(resultSet.getColumnIndex("deviceName"))
                        let cpuCluster = resultSet.getString(resultSet.getColumnIndex("cpuCluster"))
                        let uploadTaskId = resultSet.getString(resultSet.getColumnIndex("uploadTaskId"))
                        let syncStatusStr=resultSet.getColumnIndex("syncStatus")
                        let syncStatus = syncStatusStr ? resultSet.getString(syncStatusStr) : '0'
                        let tGeneralInfo = new TGeneralInfo(
                            sessionId, taskId, appName, appVersion, packageName, Number(startTime).valueOf(), Number(endTime).valueOf(), testDuration, taskName,
                            upStatus, deviceName, cpuCluster, uploadTaskId
                        )
                        tGeneralInfo.board = board
                        tGeneralInfo.deviceTypeName = deviceTypeName
                        tGeneralInfo.brand = brand
                        tGeneralInfo.version = version
                        tGeneralInfo.sn = sn
                        tGeneralInfo.upStatus = upStatus
                        tGeneralInfo.projectId = projectId
                        tGeneralInfo.syncStatus = syncStatus
                        results.push(tGeneralInfo)
                    }
                })
                return results
    },

    //查询表( T_INDEX_INFO) 2022-02-23 改为传时间戳
    async queryData(dbPath: string): Promise<Array<TIndexInfo>> {
        const queryColumns = [
            "timestamp", "taskId", "shellBackTemp", "shellFrameTemp", "shellFrontTemp", "socThermalTemp", "systemHTemp", "gpuTemp", "ambientTemp", "batteryTemp","ddrFrequency",
            "cpu0Frequency", "cpu1Frequency", "cpu2Frequency", "cpu3Frequency", "cpu4Frequency", "cpu5Frequency", "cpu6Frequency", "cpu7Frequency","cpu8Frequency", "cpu9Frequency", "cpu10Frequency", "cpu11Frequency",
            "cpu0Load", "cpu1Load", "cpu2Load", "cpu3Load", "cpu4Load", "cpu5Load", "cpu6Load", "cpu7Load", "cpu8Load", "cpu9Load", "cpu10Load", "cpu11Load",
            "gpuLoad", "gpuFrequency", "currentNow", "voltageNow",
            "pss","memTotal","memFree","memAvailable","gpuPss","graphicPss","arktsHeapPss","nativeHeapPss","heapSize","heapAlloc","heapFree","privateClean","privateDirty","sharedClean","sharedDirty","stackPss","swapPss","swap",
            "fps", "fpsJitters", "networkUpSpeed","networkDownSpeed",
            "cpu1ClusterFre", "cpu2ClusterFre", "cpu3ClusterFre"
        ]
        let results = Array<TIndexInfo>()
        const STORE_CONFIG: relationalStore.StoreConfig = {
            name: dbPath,
            securityLevel: relationalStore.SecurityLevel.S1
        };
        return relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG).then(rdbStore => {
            return rdbStore.query(new relationalStore.RdbPredicates('t_index_info').orderByAsc('timestamp'))
        }).then(resultSet => {
                while (resultSet.goToNextRow()) {
                    let timestamp = resultSet.getString(resultSet.getColumnIndex("timestamp"))
                    let taskId = resultSet.getString(resultSet.getColumnIndex("taskId"))
                    let shellBackTemp = resultSet.getString(resultSet.getColumnIndex("shellBackTemp"))
                    let shellFrameTemp = resultSet.getString(resultSet.getColumnIndex("shellFrameTemp"))
                    let shellFrontTemp = resultSet.getString(resultSet.getColumnIndex("shellFrontTemp"))
                    let socThermalTemp = resultSet.getString(resultSet.getColumnIndex("socThermalTemp"))
                    let systemHTemp = resultSet.getString(resultSet.getColumnIndex("systemHTemp"))
                    let gpuTemp = resultSet.getString(resultSet.getColumnIndex("gpuTemp"))
                    let ambientTemp = resultSet.getString(resultSet.getColumnIndex("ambientTemp"))
                    let batteryTemp = resultSet.getString(resultSet.getColumnIndex("batteryTemp"))
                    let ddrFrequency = resultSet.getString(resultSet.getColumnIndex("ddrFrequency"))
                    let cpu0Frequency = resultSet.getString(resultSet.getColumnIndex("cpu0Frequency"))
                    let cpu1Frequency = resultSet.getString(resultSet.getColumnIndex("cpu1Frequency"))
                    let cpu2Frequency = resultSet.getString(resultSet.getColumnIndex("cpu2Frequency"))
                    let cpu3Frequency = resultSet.getString(resultSet.getColumnIndex("cpu3Frequency"))
                    let cpu4Frequency = resultSet.getString(resultSet.getColumnIndex("cpu4Frequency"))
                    let cpu5Frequency = resultSet.getString(resultSet.getColumnIndex("cpu5Frequency"))
                    let cpu6Frequency = resultSet.getString(resultSet.getColumnIndex("cpu6Frequency"))
                    let cpu7Frequency = resultSet.getString(resultSet.getColumnIndex("cpu7Frequency"))

                    let cpu8Frequency = resultSet.getString(resultSet.getColumnIndex("cpu8Frequency"))
                    let cpu9Frequency = resultSet.getString(resultSet.getColumnIndex("cpu9Frequency"))
                    let cpu10Frequency = resultSet.getString(resultSet.getColumnIndex("cpu10Frequency"))
                    let cpu11Frequency = resultSet.getString(resultSet.getColumnIndex("cpu11Frequency"))

                    let cpu0Load = resultSet.getString(resultSet.getColumnIndex("cpu0Load"))
                    let cpu1Load = resultSet.getString(resultSet.getColumnIndex("cpu1Load"))
                    let cpu2Load = resultSet.getString(resultSet.getColumnIndex("cpu2Load"))
                    let cpu3Load = resultSet.getString(resultSet.getColumnIndex("cpu3Load"))
                    let cpu4Load = resultSet.getString(resultSet.getColumnIndex("cpu4Load"))
                    let cpu5Load = resultSet.getString(resultSet.getColumnIndex("cpu5Load"))
                    let cpu6Load = resultSet.getString(resultSet.getColumnIndex("cpu6Load"))
                    let cpu7Load = resultSet.getString(resultSet.getColumnIndex("cpu7Load"))

                    let cpu8Load = resultSet.getString(resultSet.getColumnIndex("cpu8Load"))
                    let cpu9Load = resultSet.getString(resultSet.getColumnIndex("cpu9Load"))
                    let cpu10Load = resultSet.getString(resultSet.getColumnIndex("cpu10Load"))
                    let cpu11Load = resultSet.getString(resultSet.getColumnIndex("cpu11Load"))

                    let cpu1ClusterFre = resultSet.getString(resultSet.getColumnIndex("cpu1ClusterFre"))
                    let cpu2ClusterFre = resultSet.getString(resultSet.getColumnIndex("cpu2ClusterFre"))
                    let cpu3ClusterFre = resultSet.getString(resultSet.getColumnIndex("cpu3ClusterFre"))

                    let gpuLoad = resultSet.getString(resultSet.getColumnIndex("gpuLoad"))
                    let gpuFrequency = resultSet.getString(resultSet.getColumnIndex("gpuFrequency"))
                    let currentNow = resultSet.getString(resultSet.getColumnIndex("currentNow"))
                    let voltageNow = resultSet.getString(resultSet.getColumnIndex("voltageNow"))

                    let pss = resultSet.getString(resultSet.getColumnIndex("pss"))
                    let memTotalIndex=resultSet.getColumnIndex("memTotal")
                    let memTotal = memTotalIndex !=-1 ? resultSet.getString(memTotalIndex) : ""
                    let memFreeIndex=resultSet.getColumnIndex("memFree")
                    let memFree = memFreeIndex != -1 ? resultSet.getString(memFreeIndex) : ""
                    let memAvailableIndex=resultSet.getColumnIndex("memAvailable")
                    let memAvailable = memAvailableIndex != -1 ? resultSet.getString(memAvailableIndex) : ""
                    let gpuPssIndex=resultSet.getColumnIndex("gpuPss")
                    let gpuPss = gpuPssIndex != -1 ?resultSet.getString(gpuPssIndex) : ""
                    let graphicPssIndex=resultSet.getColumnIndex("graphicPss")
                    let graphicPss = graphicPssIndex != -1 ? resultSet.getString(graphicPssIndex) : ""
                    let arktsHeapPssIndex=resultSet.getColumnIndex("arktsHeapPss")
                    let arktsHeapPss = arktsHeapPssIndex != -1 ? resultSet.getString(arktsHeapPssIndex) : ""
                    let nativeHeapPssIndex=resultSet.getColumnIndex("nativeHeapPss")
                    let nativeHeapPss = nativeHeapPssIndex != -1 ? resultSet.getString(nativeHeapPssIndex) : ""
                    let heapSizeIndex=resultSet.getColumnIndex("heapSize")
                    let heapSize = heapSizeIndex != -1 ? resultSet.getString(heapSizeIndex) : ""
                    let heapAllocIndex=resultSet.getColumnIndex("heapAlloc")
                    let heapAlloc = heapAllocIndex != -1 ? resultSet.getString(heapAllocIndex) : ""
                    let heapFreeIndex=resultSet.getColumnIndex("heapFree")
                    let heapFree = heapFreeIndex != -1 ? resultSet.getString(heapFreeIndex) : ""
                    let privateCleanIndex=resultSet.getColumnIndex("privateClean")
                    let privateClean = privateCleanIndex != -1 ? resultSet.getString(privateCleanIndex) : ""
                    let privateDirtyIndex=resultSet.getColumnIndex("privateDirty")
                    let privateDirty = privateDirtyIndex != -1 ? resultSet.getString(privateDirtyIndex) : ""
                    let sharedCleanIndex=resultSet.getColumnIndex("sharedClean")
                    let sharedClean = sharedCleanIndex != -1 ? resultSet.getString(sharedCleanIndex) : ""
                    let sharedDirtyIndex=resultSet.getColumnIndex("sharedDirty")
                    let sharedDirty = sharedDirtyIndex != -1 ? resultSet.getString(sharedDirtyIndex) : ""
                    let stackPssIndex=resultSet.getColumnIndex("stackPss")
                    let stackPss = stackPssIndex != -1 ? resultSet.getString(stackPssIndex) : ""
                    let swapPssIndex=resultSet.getColumnIndex("swapPss")
                    let swapPss = swapPssIndex != -1 ? resultSet.getString(swapPssIndex) : ""
                    let swapIndex=resultSet.getColumnIndex("swap")
                    let swap = swapIndex != -1 ? resultSet.getString(resultSet.getColumnIndex("swap")) : ""

                    let fps = resultSet.getString(resultSet.getColumnIndex("fps"))
                    let fpsJitters = resultSet.getString(resultSet.getColumnIndex("fpsJitters"))

                    let networkUpSpeed = resultSet.getString(resultSet.getColumnIndex("networkUpSpeed"))
                    let networkDownSpeed = resultSet.getString(resultSet.getColumnIndex("networkDownSpeed"))

                    results.push(new TIndexInfo(
                        timestamp,
                        taskId,
                        cpu0Frequency, cpu1Frequency, cpu2Frequency, cpu3Frequency, cpu4Frequency, cpu5Frequency, cpu6Frequency, cpu7Frequency,
                        cpu8Frequency, cpu9Frequency, cpu10Frequency, cpu11Frequency,
                        cpu0Load, cpu1Load, cpu2Load, cpu3Load, cpu4Load, cpu5Load, cpu6Load, cpu7Load,
                        cpu8Load, cpu9Load, cpu10Load, cpu11Load,
                        gpuFrequency, gpuLoad,
                        ddrFrequency,
                        shellFrameTemp, shellFrontTemp, shellBackTemp, socThermalTemp, systemHTemp, gpuTemp, ambientTemp, batteryTemp,
                        currentNow, voltageNow,
                        pss,memTotal,memFree,memAvailable,gpuPss,graphicPss,arktsHeapPss,nativeHeapPss,heapSize,heapAlloc,heapFree,privateClean,privateDirty,sharedClean,sharedDirty,stackPss,swapPss,swap,
                        fps,fpsJitters,
                        networkUpSpeed,networkDownSpeed, cpu1ClusterFre, cpu2ClusterFre, cpu3ClusterFre
                    ))
                }
            SPLogger.INFO(TAG, "query T_INDEX_INFO :" +results.length)
            return results
        })
    },


    // 生成表 (SceneInfo)
    async getSceneInfo(dbPath: string): Promise<Array<SceneInfo>> {
        var sceneInfo: SceneInfo = new SceneInfo()
        sceneInfo.setDefaultValue();
        let results = Array<SceneInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: dbPath,
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG).then(async (rdbStore) => {
                let strSQL: string = "SELECT ROUND(AVG((CASE WHEN currentNow < 0 THEN (-1 * currentNow) ELSE currentNow END)),2) as averageCurrentNow," +
                "ROUND(AVG((CASE WHEN (voltageNow * currentNow) < 0 THEN (voltageNow * currentNow)/(-3.8) ELSE (voltageNow * currentNow)/(3.8) END)),2) as electricity," +
                "ROUND(MAX(systemHTemp),2) as maxSystemTem," +
                "ROUND(MAX(systemHTemp) - MIN(systemHTemp),2) as systemTemRise," +
                "ROUND(MAX(shellFrameTemp),3) as maxShellTemp," +
                "ROUND(MAX(shellFrameTemp) - MIN(shellFrameTemp),3) as shellTemRise," +
                "ROUND(avg(cpu0Frequency/1000),3) as cpuC1Frequency," +
                "ROUND(avg(cpu4Frequency/1000),3) as cpuC2Frequency," +
                "ROUND(avg(cpu7Frequency/1000),3) as cpuC3Frequency," +
                "ROUND(avg(gpuFrequency/1000000),3) as gpuFrequency," +
                "ROUND(avg(fps), 3)as averageFrameRate," +
                "ROUND(avg(ddrFrequency/1000000),3) as ddrFrequency FROM t_index_info"
                return rdbStore.querySql(strSQL)
            }).then(resultSet => {
                resultSet.goToFirstRow()
                sceneInfo.setAverageCurrentNow(resultSet.getString(resultSet.getColumnIndex("averageCurrentNow")))
                sceneInfo.setElectricity(resultSet.getString(resultSet.getColumnIndex("electricity")))
                sceneInfo.setMaxSystemTem(resultSet.getString(resultSet.getColumnIndex("maxSystemTem")))
                sceneInfo.setSystemTemRise(resultSet.getString(resultSet.getColumnIndex("systemTemRise")))
                sceneInfo.setMaxShellTemp(resultSet.getString(resultSet.getColumnIndex("maxShellTemp")))
                sceneInfo.setShellTemRise(resultSet.getString(resultSet.getColumnIndex("shellTemRise")))
                sceneInfo.setCpuC1Frequency(resultSet.getString(resultSet.getColumnIndex("cpuC1Frequency")))
                sceneInfo.setCpuC2Frequency(resultSet.getString(resultSet.getColumnIndex("cpuC2Frequency")))
                sceneInfo.setCpuC3Frequency(resultSet.getString(resultSet.getColumnIndex("cpuC3Frequency")))
                sceneInfo.setGpuFrequency(resultSet.getString(resultSet.getColumnIndex("gpuFrequency")))
                sceneInfo.setDdrFrequency(resultSet.getString(resultSet.getColumnIndex("ddrFrequency")))
                sceneInfo.setAverageFrameRate(resultSet.getString(resultSet.getColumnIndex("averageFrameRate")))
                results.push(sceneInfo)
                return results
            })
        } catch (err) {
            return results
        }
    },


    // 更新taskId
    async updateGeneralInfo(taskId, sessionId): Promise<void> {
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: dbName,
                securityLevel: relationalStore.SecurityLevel.S1
            };
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG).then(async (rdbStore) => {
                let strSQL: string = "UPDATE t_general_info SET taskId = ? WHERE sessionId LIKE?"
                return rdbStore.executeSql(strSQL, [taskId, sessionId + ''])
            })
        }catch (err) {
            SPLogger.ERROR(TAG, "updateGeneralInfo err:" +err)
        }
    },

    async updateIndexInfo(dbTimeStamp, taskId): Promise<void> {
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: dbTimeStamp,
                securityLevel: relationalStore.SecurityLevel.S1
            };
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG).then(async (rdbStore) => {
                let strSQL: string = "UPDATE t_index_info SET taskId =?"
                return rdbStore.executeSql(strSQL, [taskId])
            })
        }catch (err) {
            SPLogger.ERROR(TAG, "updateIndexInfo err:" +err)
        }
    },


    /**
     * Array<GPData> 封装为TIndexInfo
     * @param gpDatas
     */
    gpArray2Index(gpDatas: Array<GPData>): TIndexInfo{

        var tIndexInfo: TIndexInfo = new TIndexInfo()
        tIndexInfo.setDefaultValue();
        if(globalThis.taskId != null){
            tIndexInfo.setTaskId(globalThis.taskId.toString())
        }
        tIndexInfo.setTimeStamp(new Date().getTime().toString())
        if (gpDatas != null) {
            for (var index = 0; index < gpDatas.length; index++) {
                let curGPData: GPData = gpDatas[index]
                let map = curGPData.values

                switch (curGPData.moduleType) {
                    case "CPU":
                        tIndexInfo.setCPUData(
                        map.get("cpu0Freq"),
                        map.get("cpu1Freq"),
                        map.get("cpu2Freq"),
                        map.get("cpu3Freq"),
                        map.get("cpu4Freq"),
                        map.get("cpu5Freq"),
                        map.get("cpu6Freq"),
                        map.get("cpu7Freq"),
                        map.get("cpu8Freq"),
                        map.get("cpu9Freq"),
                        map.get("cpu10Freq"),
                        map.get("cpu11Freq"),
                        globalThis.cpuCoreNum
                        )
                        break;
                    case "CPULoad":
                        tIndexInfo.setCPULoadData(
                        map.get("cpu0Load"),
                        map.get("cpu1Load"),
                        map.get("cpu2Load"),
                        map.get("cpu3Load"),
                        map.get("cpu4Load"),
                        map.get("cpu5Load"),
                        map.get("cpu6Load"),
                        map.get("cpu7Load"),
                        map.get("cpu8Load"),
                        map.get("cpu9Load"),
                        map.get("cpu10Load"),
                        map.get("cpu11Load"),
                        globalThis.cpuCoreNum
                        )
                        break;
                    case "GPU":
                        tIndexInfo.setGPUData(
                        map.get("gpuFreq"),
                        map.get("gpuLoad")
                        )
                        break;
                    case "DDR":
                        tIndexInfo.setDDRData(
                        map.get("ddrFreq")
                        )
                        break;
                    case "Temp":
                        tIndexInfo.setTempData(
                        map.get("shell_frame"),
                        map.get("shell_front"),
                        map.get("shell_back"),
                        map.get("soc_thermal"),
                        map.get("system_h"),
                        map.get("gpu"),
                        map.get("Battery")

                        )
                        break;
                    case "Power":
                        tIndexInfo.setPowerData(
                        map.get("current_now"),
                        map.get("voltage_now"),
                        map.get("capacity"),
                        map.get("status")
                        )
                        break;
                    case "RAM":
                        tIndexInfo.setRamData(
                            map.get("pss"),
                            map.get("memTotal"),
                            map.get("memFree"),
                            map.get("memAvailable"),
                            map.get("gpuPss"),
                            map.get("graphicPss"),
                            map.get("arktsHeapPss"),
                            map.get("nativeHeapPss"),
                            map.get("heapSize"),
                            map.get("heapAlloc"),
                            map.get("heapFree"),
                            map.get("privateClean"),
                            map.get("privateDirty"),
                            map.get("sharedClean"),
                            map.get("sharedDirty"),
                            map.get("stackPss"),
                            map.get("swapPss"),
                            map.get("swap")
                        )
                        break;
                    case "FPS":
                        tIndexInfo.setFpsData(
                        map.get("fps"), map.get("fpsJitters"))
                        break;
                    case "NetWork":
                        tIndexInfo.setNetWorkData(
                        map.get("netSpeedUp"), map.get("netSpeedDown"))
                        break;
                }
            }
        }

        return tIndexInfo
    },

    //插入表(task_powersensor_info)
     insertPowerSensor(tableName: string, pathSuffix: number, tPowerSenspor: TPowerSensorInfo) {
        SPLogger.INFO("TAG","resultSet query_applications_display-----tPowerSenspor" + JSON.stringify(tPowerSenspor))
        var strMap = new Map;
        for (let k of Object.keys(tPowerSenspor)) {
            strMap.set(k, tPowerSenspor[k]);
        }
        const STORE_CONFIG: relationalStore.StoreConfig = {
            name: pathSuffix + ".db",
            securityLevel: relationalStore.SecurityLevel.S1
        }
        relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG, (err, rdbStore) => {
            SPLogger.INFO("TAG","resultSet query_applications_display-----tPowerSenspor" + JSON.stringify(pathSuffix))
            rdbStore.insert(tableName, Object.fromEntries(strMap))
        })
    },

    //插入表(task_powerapp_info)
    insertPowerAppInfo(tableName: string, pathSuffix: number, tPowerApp: TPowerAppInfo) {
        SPLogger.INFO("TAG","resultSet query_applications_display-----tPowerApp" + JSON.stringify(tPowerApp))
        var strMap = new Map;
        for (let k of Object.keys(tPowerApp)) {
            strMap.set(k, tPowerApp[k]);
        }
        const valueInsert = {
            "taskId": globalThis.taskId.toString(),
            "process": strMap.get("application"),
            "energy": strMap.get("power"),
            "percent": strMap.get("percent"),
        }
        const STORE_CONFIG: relationalStore.StoreConfig = {
            name: pathSuffix + ".db",
            securityLevel: relationalStore.SecurityLevel.S1
        }
        relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG, (err, rdbStore) => {
            SPLogger.INFO("TAG","resultSet query_applications_display-----tPowerApp" + JSON.stringify(pathSuffix))
            rdbStore.insert(tableName, valueInsert)
        })
    },

    //查询表（detailed_applications_display）
    async query_applications_display(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select sum(energy)/3600.0 power,sum(energy)/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_display " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)
                    SPLogger.INFO("TAG","resultSet query_applications_display-----display" + JSON.stringify(strSQL))
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {

                    while (resultSet.goToNextRow()) {
                        let sensor = "display"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "", sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----display" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)

        }
    },
    //查询表（task_powersensor_info）
    async query_powersensor_info(pathSuffix: number): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: pathSuffix + ".db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                         let strSQL: string = "select * " +
                        "from task_powersensor_info order by power desc  "

                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let sensor =resultSet.getString(resultSet.getColumnIndex("sensor"))
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)

        }
    },
    //查询表（detailed_applications_cpu）
    async query_applications_cpu(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select (sum(foreground_energy)+sum(background_energy))/3600.0 power, (sum(foreground_energy)+sum(background_energy))/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_cpu " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)

                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let sensor = "cpu"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----cpu" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)

        }
    },
    //查询表（detailed_applications_gpu）
    async query_applications_gpu(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select sum(energy)/3600.0 power,sum(energy)/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_gpu " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)

                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {

                    while (resultSet.goToNextRow()) {
                        let sensor = "gpu"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----gpu" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)

        }
    },
    //查询表（detailed_applications_wifi_data）
    async query_applications_wifi_data(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select (sum(foreground_energy)+sum(background_energy))/3600.0 power, (sum(foreground_energy)+sum(background_energy))/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_wifi_data " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let sensor = "wifi_data"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----wifi_data" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)

        }
    },
    //查询表（detailed_applications_system_idle）
    async query_applications_system_idle(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select sum(energy)/3600.0 power,sum(energy)/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_system_idle " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let sensor = "system_idle"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----system_idle" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)

        }
    },
    //查询表（detailed_applications_audio）
    async query_applications_audio(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select (sum(foreground_energy)+sum(background_energy))/3600.0 power, (sum(foreground_energy)+sum(background_energy))/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_audio " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let sensor = "audio"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----audio" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)

        }
    },
    //查询表（detailed_applications_dss）
    async query_applications_dss(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select sum(foreground_energy)+sum(background_energy))/3600.0 power, (sum(foreground_energy)+sum(background_energy))/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_dss " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let sensor = "dss"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----dss" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)

        }
    },
    //查询表（detailed_applications_ddr）
    async query_applications_ddr(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select (sum(foreground_energy)+sum(background_energy))/3600.0 power, (sum(foreground_energy)+sum(background_energy))/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_ddr " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {

                    while (resultSet.goToNextRow()) {
                        let sensor = "ddr"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----ddr" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)

        }
    },
    //查询表（detailed_applications_sensor）
    async query_applications_sensor(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select (sum(foreground_energy)+sum(background_energy))/3600.0 power, (sum(foreground_energy)+sum(background_energy))/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_sensor " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let sensor = "sensor"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----sensor" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)
        }
    },
    //查询表（detailed_applications_rom）
    async query_applications_rom(start_time: String, end_time: String,pkg_name:String): Promise<Array<TPowerSensorInfo>> {

        let results = Array<TPowerSensorInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select (sum(foreground_energy)+sum(background_energy))/3600.0 power, (sum(foreground_energy)+sum(background_energy))/((max(end_time)-min(start_time))/1000.0) current " +
                    "from detailed_applications_rom " +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and formatted_end_time <= " +
                    JSON.stringify(end_time) +
                    " and name = "+
                    JSON.stringify(pkg_name)
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let sensor = "rom"
                        let power = resultSet.getString(resultSet.getColumnIndex("power"))
                        let current = resultSet.getString(resultSet.getColumnIndex("current"))
                        let tPowerSensorInfo = new TPowerSensorInfo( "",  sensor, power, current,"")
                        results.push(tPowerSensorInfo)
                    }
                    SPLogger.INFO("TAG","resultSet query_applications_display-----rom" + JSON.stringify(results))
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)
        }
    },
    //查询dubai 所有进程功耗 并插入表 t_power_appinfo
    async query_applications_power_info(start_time: string, end_time: string): Promise<Array<TPowerAppInfo>> {

        let results = Array<TPowerAppInfo>()
        var strSQL:String = ""
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let sqlWhere = " where formatted_start_time >= '{startTime}'  and formatted_end_time <= '{endTime}' "
                    let sqlWhereReplace = sqlWhere.replace("{startTime}",start_time).replace("{endTime}",end_time)
                    SPLogger.ERROR("TAG","resultSet query_applications_display-----sqlWhereReplace:" + sqlWhereReplace)
                    strSQL =
                        "select formatted_start_time, formatted_end_time, name, round((foreground_energy+background_energy)/3600.0,5) as energy "+
                        "from detailed_applications_cpu "+
                        sqlWhereReplace+
                        "union all "+

                        "select formatted_start_time, formatted_end_time, name,round(energy/3600.0,5) as energy "+
                        "from detailed_applications_display "+
                        sqlWhereReplace+
                        "union all "+

                        "select formatted_start_time, formatted_end_time, name,round(energy/3600.0,5) as energy "+
                        "from detailed_applications_gpu "+
                        sqlWhereReplace+
                        "union all "+

                        "select formatted_start_time, formatted_end_time, name,round(energy/3600.0,5) as energy "+
                        "from detailed_applications_system_idle "+
                        sqlWhereReplace+
                        "union all "+

                        "select formatted_start_time, formatted_end_time, name, round((foreground_energy+background_energy)/3600.0,5) as energy "+
                        "from detailed_applications_wifi_data "+
                        sqlWhereReplace+
                        "union all "+

                        "select formatted_start_time, formatted_end_time, name, round((foreground_energy+background_energy)/3600.0,5) as energy "+
                        "from detailed_applications_sensor "+
                        sqlWhereReplace+
                        "union all "+

                        "select formatted_start_time, formatted_end_time, name, round((foreground_energy+background_energy)/3600.0,5) as energy "+
                        "from detailed_applications_audio "+
                        sqlWhereReplace

                    return rdbStore.querySql(strSQL.toString())
                })
                .then(resultSet => {
                    SPLogger.ERROR("TAG","resultSet query_applications_display-----result L:" + resultSet.rowCount)
                    let tMap:Map<String,String> = new Map
                    let totalSumEnergy:number = 0.0
                    while (resultSet.goToNextRow()) {
                        let sum_energy = resultSet.getString(resultSet.getColumnIndex("energy"))
                        totalSumEnergy = totalSumEnergy + Number(sum_energy)
                        let name = resultSet.getString(resultSet.getColumnIndex("name"))
                        let existElement = tMap.get(name)
                        if(existElement!=undefined){
                            //存在则修改
                            let newP:Number = Number(existElement) + Number(sum_energy)
                            tMap.set(name,newP.toString())
                        }else{
                            tMap.set(name,sum_energy)
                        }
                    }

                    //遍历去重相加后的arr
                    for(let [name,power] of tMap){
                        let percent = Number(power)*100 / totalSumEnergy
                        let tPowerAppInfo = new TPowerAppInfo("", "", name, power, "0", percent.toFixed(5))
                        SPLogger.ERROR("TAG","resultSet query_applications_display-----result0:" + JSON.stringify(tPowerAppInfo))
                        results.push(tPowerAppInfo)
                    }
                    return results.sort((a, b) => parseFloat(b.power.toString()) -  parseFloat(a.power.toString())).slice(0,20)
                })
                .then(results =>{
                    SPLogger.ERROR("TAG","resultSet query_applications_display-----result after:" + results.length)
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display err22222:"+err)
        }
    },

    //查询 t_powerapp_info
    async query_powerapp_info(pathSuffix: number): Promise<Array<TPowerAppInfo>> {


        let results = Array<TPowerAppInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: pathSuffix + ".db",
                securityLevel: relationalStore.SecurityLevel.S1
            }
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async(rdbStore) => {
                    let strSQL: string = "select * " +
                    "from task_powerapp_info order by energy desc  "

                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while (resultSet.goToNextRow()) {
                        let process =resultSet.getString(resultSet.getColumnIndex("process"))
                        let energy = resultSet.getString(resultSet.getColumnIndex("energy"))
                        let percent = resultSet.getString(resultSet.getColumnIndex("percent"))

                        let tPowerAppInfo = new TPowerAppInfo("", "", process, energy, "0", percent)
                        results.push(tPowerAppInfo)
                    }
                    return results
                })
        } catch (err) {
            SPLogger.ERROR(TAG,"resultSet query_applications_display query_powerapp_info:"+err)
        }
    },

    //dubai 查询 线程功耗 t_powerthread_info
    async query_powerthread_info(start_time: String, end_time: String, pkg_name: String): Promise<Array<TPowerAppInfo>>{
        let results = Array<TPowerAppInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "dubai.db",
                securityLevel: relationalStore.SecurityLevel.S1
            };
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async (rdbStore) => {
                    let strSQL: string = "select formatted_start_time, formatted_end_time, name, round((foreground_energy+background_energy)/3600.0,5) as energy" +
                    "from detailed_applications_cpu" +
                    "where formatted_start_time >= " +
                    JSON.stringify(start_time) +
                    " and name like 'Thread_%' " +
                    "order by energy desc"
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while(resultSet.goToNextRow()){
                        let process = resultSet.getString(resultSet.getColumnIndex("name"))
                        let energy = resultSet.getString(resultSet.getColumnIndex("energy"))
                        let tPowerAppInfo = new TPowerAppInfo("", "", process, energy, "0", "0")
                        results.push(tPowerAppInfo)
                    }
                    return results
                })
        } catch (err) {

        }
    },

    // dubai 线程功耗本地查询
    // 查询 t_powerapp_info
    async query_powerthread_info_local(pathSuffix: number): Promise<Array<TPowerAppInfo>> {
        let results = Array<TPowerAppInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: pathSuffix + ".db",
                securityLevel: relationalStore.SecurityLevel.S1
            };
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(async (rdbStore) => {
                    let strSQL: string = "select * " +
                    "from task_powerthread_info order by energy desc"
                    return rdbStore.querySql(strSQL)
                })
                .then(resultSet => {
                    while(resultSet.goToNextRow()){
                        let process = resultSet.getString(resultSet.getColumnIndex("process"))
                        let energy = resultSet.getString(resultSet.getColumnIndex("energy"))
                        let percent = resultSet.getString(resultSet.getColumnIndex("percent"))
                        let tPowerAppInfo = new TPowerAppInfo("", "", process, energy, "0", percent)
                        results.push(tPowerAppInfo)
                    }
                    return results
                })
        } catch (err) {

        }
    },
    // 插入表 (t_user_info)
    async insertUserInfo(tUserInfo: UserInfo) {
        var tableName = "t_user_info"
        var strMap = new Map;
        for (let k of Object.keys(tUserInfo)){
            strMap.set(k, tUserInfo[k]);
        }
        const STORE_CONFIG: relationalStore.StoreConfig = {
            name: "gp.db",
            securityLevel: relationalStore.SecurityLevel.S1
        };
        relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG, (err, rdbStore) => {
            try {
                rdbStore.insert(tableName, Object.fromEntries(strMap))
            } catch(err){
            }
        })
    },

    // 查询表 (t_user_info)
    async queryUserInfo(): Promise<Array<UserInfo>> {
        let results = Array<UserInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: "gp.db",
                securityLevel: relationalStore.SecurityLevel.S1
            };
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(rdbStore => {
                    let predicates = new relationalStore.RdbPredicates("t_user_info")
                    return rdbStore.query(predicates)
                })
                .then(resultSet => {
                    while(resultSet.goToNextRow()){
                        let token = resultSet.getString(resultSet.getColumnIndex("token"))
                        let userId = resultSet.getString(resultSet.getColumnIndex("userId"))
                        let user = resultSet.getString(resultSet.getColumnIndex("user"))
                        let projectId = resultSet.getString(resultSet.getColumnIndex("projectId"))
                        let loginTime = resultSet.getString(resultSet.getColumnIndex("loginTime"))
                        let refreshToken = resultSet.getString(resultSet.getColumnIndex("refreshToken"))
                        let openID = resultSet.getString(resultSet.getColumnIndex("openID"))
                        let unionID = resultSet.getString(resultSet.getColumnIndex("unionID"))
                        let userType = resultSet.getString(resultSet.getColumnIndex("userType"))
                        let headerPic = resultSet.getString(resultSet.getColumnIndex('headPicUrl'))
                        let userInfo = new UserInfo(token, userId, user, projectId, loginTime)
                        userInfo.refreshToken=refreshToken
                        userInfo.openID=openID
                        userInfo.unionID=unionID
                        userInfo.userType = userType as UserType
                        userInfo.headPicUrl = headerPic
                        results.push(userInfo)
                    }
                    return results;
                })
        } catch (err) {
            console.log(err)
        }
        return results;
    },

    // 删除表 (t_user_info)
    async deleteUserInfo() {
        const STORE_CONFIG: relationalStore.StoreConfig = {
            name: 'gp.db',
            securityLevel: relationalStore.SecurityLevel.S1
        };
        relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG, (err,rdbStore)=>{
            rdbStore.executeSql(sql_t_user_info_delete, null)
        })
    },
    //更新表数据 (t_user_info)
    async updateUserInfo(tUserInfo:UserInfo) {
        var tableName = "t_user_info"
        var strMap = new Map;
        for (let k of Object.keys(tUserInfo)){
            strMap.set(k, tUserInfo[k]);
        }
        const STORE_CONFIG: relationalStore.StoreConfig = {
            name: 'gp.db',
            securityLevel: relationalStore.SecurityLevel.S1
        };
        return  relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG,async (err,rdbStore)=>{
            let rs = await rdbStore.update(Object.fromEntries(strMap),new relationalStore.RdbPredicates(tableName))
            SPLogger.DEBUG(TAG, "update t_user_info :" +rs)
            return rs
        })
    },
    // 查询表 (t_perform_info)
    async queryPerformInfo(): Promise<Array<PerformInfo>> {
        let results = Array<PerformInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: dbName,
                securityLevel: relationalStore.SecurityLevel.S1
            };
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(rdbStore => {
                    let predicates = new relationalStore.RdbPredicates("t_perform_info")
                    return rdbStore.query(predicates, ["id", "name", "type", "package", "value", "startTime", "endTime"])
                })
                .then(resultSet => {
                    while(resultSet.goToNextRow()){
                        let id = resultSet.getString(resultSet.getColumnIndex("id"))
                        let name = resultSet.getString(resultSet.getColumnIndex("name"))
                        let type = resultSet.getString(resultSet.getColumnIndex("type"))
                        let packageName = resultSet.getString(resultSet.getColumnIndex("package"))
                        let value = resultSet.getString(resultSet.getColumnIndex("value"))
                        let startTime = resultSet.getString(resultSet.getColumnIndex("startTime"))
                        let endTime = resultSet.getString(resultSet.getColumnIndex("endTime"))
                        let performInfo = new PerformInfo(id, name, type, packageName, value, startTime, endTime)
                        results.push(performInfo)
                    }
                    return results;
                })
        } catch (err) {

        }
        return results;
    },

    // 查询表 (t_FrameRate_info)帧率测试信息
    async queryFrameRateInfo(): Promise<Array<FrameRateInfo>> {
        let results = Array<FrameRateInfo>()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: dbName,
                securityLevel: relationalStore.SecurityLevel.S1
            };
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(rdbStore => {
                    let predicates = new relationalStore.RdbPredicates("t_FrameRate_info")
                    return rdbStore.query(predicates, ["id", "name", "type", "package", "value", "startTime", "endTime"])
                })
                .then(resultSet => {
                    while(resultSet.goToNextRow()){
                        let id = resultSet.getString(resultSet.getColumnIndex("id"))
                        let name = resultSet.getString(resultSet.getColumnIndex("name"))
                        let type = resultSet.getString(resultSet.getColumnIndex("type"))
                        let packageName = resultSet.getString(resultSet.getColumnIndex("package"))
                        let value = resultSet.getString(resultSet.getColumnIndex("value"))
                        let startTime = resultSet.getString(resultSet.getColumnIndex("startTime"))
                        let endTime = resultSet.getString(resultSet.getColumnIndex("endTime"))
                        let frameRateInfo = new FrameRateInfo(id, name, type, packageName, value, startTime, endTime)
                        results.push(frameRateInfo)
                    }
                    return results;
                })
        } catch (err) {

        }
        return results;
    },
    // 查询表t_gpu_counter_info
    async queryGPUCounterCSVFileInfo(pathSuffix: String): Promise<Object> {
        let results = new Object()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: pathSuffix + '.db',
                securityLevel: relationalStore.SecurityLevel.S1
            };
            SPLogger.DEBUG(TAG,'query t_gpu_counter_info config：'+STORE_CONFIG.name+','+STORE_CONFIG.securityLevel)
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(rdbStore => {
                    // let sql = `select * from t_gpu_counter_info where id = '${pathSuffix}'`
                    // return rdbStore.querySql(sql)
                    return rdbStore.query(new relationalStore.RdbPredicates('t_gpu_counter_info'))
                })
                .then(resultSet => {
                    SPLogger.DEBUG(TAG,'query t_gpu_counter_info result: count '+resultSet.rowCount)
                    while (resultSet.goToNextRow()) {
                        let id = resultSet.getString(resultSet.getColumnIndex("id"))
                        let battery = resultSet.getString(resultSet.getColumnIndex("csvFileName"))
                        results = {'id':id,'csvFileName':battery}
                        SPLogger.DEBUG(TAG,'query t_gpu_counter_info result: '+JSON.stringify(results))
                    }
                    SPLogger.DEBUG(TAG,'query t_gpu_counter_info result result: '+JSON.stringify(results))
                    return results;
                })
        }catch (err) {
            SPLogger.ERROR(TAG, "query t_gpu_counter_info err:" +err)
        }
        return results;
    },
    // 查询表t_gpu_counter_info
    // async queryGPUCounterCSVFileInfo(pathSuffix: String): Promise<Object> {
    //     let results = new Object()
    //     try {
    //         let report_dir = globalThis.abilityContext.getApplicationContext().filesDir + '/' + pathSuffix;
    //         let options={
    //             "recursion": false,
    //             "listNum": 0,
    //             "filter": {
    //                 "suffix": [".csv"],
    //                 "displayName": ["gpu_counter*"],
    //             }}
    //         return fs.listFile(report_dir,options).then(rs=>{
    //             if (rs.length>0) {
    //                 results = {'id':pathSuffix,'csvFileName':rs.join(',')}
    //             }
    //             return results
    //         })
    //     }catch (err) {
    //         SPLogger.ERROR(TAG, "query t_gpu_counter_info err:" +err)
    //     }
    //     return results;
    // },
    //插入表t_gpu_counter_info
    insertGPUCounterCSVFileInfo(tableName: string, pathSuffix: number, csvFile: String) {
        SPLogger.DEBUG(TAG,'insert gpu_counter csv,tableName: ' + tableName)
        SPLogger.DEBUG(TAG,'insert gpu_counter csv,id: ' + pathSuffix.toString())
        SPLogger.DEBUG(TAG,'insert gpu_counter csv,csvFileName: ' + csvFile)
        let config = new DaoConfig()
        config.setDbName(pathSuffix + '.db')
        config.setTableName(tableName)
        let db = new DbUtils(config)
        if (csvFile.length>0) {
            var strMap = new Map;
            strMap.set('id',pathSuffix.toString())
            strMap.set('csvFileName',csvFile)
            const valueInsert = Object.fromEntries(strMap)
            db.save(valueInsert)
            SPLogger.DEBUG(TAG,'insert gpu_counter csv,sql value: ' + JSON.stringify(valueInsert))
        }else{
            SPLogger.DEBUG(TAG,'insert gpu_counter failed,csvFileName is empty: ')
        }

    },
    // 查询表 (t_used_res_info)电量 流量
    async queryBatteryNetDataInfo(pathSuffix: String): Promise<Object> {
        let results = new Object()
        try {
            const STORE_CONFIG: relationalStore.StoreConfig = {
                name: pathSuffix + '.db',
                securityLevel: relationalStore.SecurityLevel.S1
            };
            SPLogger.DEBUG(TAG,'query t_used_res_info config：'+STORE_CONFIG.name+','+STORE_CONFIG.securityLevel)
            return await relationalStore.getRdbStore(globalThis.abilityContext, STORE_CONFIG)
                .then(rdbStore => {
                    // let sql = `select * from t_used_res_info where id = '${pathSuffix}'`
                    // return rdbStore.querySql(sql)
                    return rdbStore.query(new relationalStore.RdbPredicates('t_used_res_info'))
                })
                .then(resultSet => {
                    SPLogger.DEBUG(TAG,'query t_used_res_info result: count '+resultSet.rowCount)
                    while (resultSet.goToNextRow()) {
                        let id = resultSet.getString(resultSet.getColumnIndex("id"))
                        let battery = resultSet.getString(resultSet.getColumnIndex("battery"))
                        let networkUp = resultSet.getString(resultSet.getColumnIndex("networkUp"))
                        let networkDown = resultSet.getString(resultSet.getColumnIndex("networkDown"))
                        results = {'id':id,'battery':battery,'networkUp':networkUp,'networkDown':networkDown}
                        SPLogger.DEBUG(TAG,'query t_used_res_info result: '+JSON.stringify(results))
                    }
                    SPLogger.DEBUG(TAG,'query t_used_res_info return result: '+JSON.stringify(results))
                    return results;
                })
        }catch (err) {
            SPLogger.ERROR(TAG, "query t_used_res_info err:" +err)
        }
        return results;
    },
    //插入表(t_used_res_info)
    insertBatteryNetData(tableName: string, pathSuffix: number, battery: String, networkUp:String,networkDown:String) {
        SPLogger.DEBUG(TAG,'insert t_used_res_info,tableName: ' + tableName)
        SPLogger.DEBUG(TAG,'insert t_used_res_info,id: ' + pathSuffix.toString())
        SPLogger.DEBUG(TAG,'insert t_used_res_info,battery: ' + battery)
        SPLogger.DEBUG(TAG,'insert t_used_res_info,networkUp: ' + networkUp)
        SPLogger.DEBUG(TAG,'insert t_used_res_info,networkDown: ' + networkDown)
        let config = new DaoConfig()
        config.setDbName(pathSuffix + '.db')
        config.setTableName(tableName)
        let db = new DbUtils(config)
        var strMap = new Map;
        strMap.set('id',pathSuffix.toString())
        strMap.set('battery',battery)
        strMap.set('networkUp',networkUp)
        strMap.set('networkDown',networkDown)
        const valueInsert = Object.fromEntries(strMap)
        db.save(valueInsert)
        SPLogger.DEBUG(TAG,'insert t_used_res_info,sql value: ' + JSON.stringify(valueInsert))
    },
}
